package top.yuhaitao.luence.controller.lucene;

import com.alibaba.fastjson2.JSON;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.IntPoint;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexableField;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.wltea.analyzer.lucene.IKAnalyzer;

import java.nio.file.Paths;
import java.util.List;

/**
 * @author ht.yu
 */
@RestController
@RequestMapping("/skuSearch")
public class SkuSearchController {

    private static final String path = "D://lucene_index";


    @RequestMapping("/select")
    public String select() throws Exception {
        //、创建分词器
        Analyzer analyzer = new IKAnalyzer();
        ///14. 创建Directory目录对象，指定索引库的位置
        Directory dir = FSDirectory.open(Paths.get(path));

//        、创建查询对象
        QueryParser queryParser = new QueryParser("name", analyzer);
// 多关键词查询
        Query query = queryParser.parse("name: 华为 AND 手机");

///15. 创建输入流
        IndexReader reader = DirectoryReader.open(dir);
//        116. 创建搜索对象
        IndexSearcher indexSearcher = new IndexSearcher(reader);
//        、搜索并返回结果
        TopDocs topDocs = indexSearcher.search(query, 10);
        ScoreDoc[] scoreDocs = topDocs.scoreDocs;
        for (ScoreDoc scoreDoc : scoreDocs) {
            int id = scoreDoc.doc;
            Document doc = indexSearcher.doc(id);
            List<IndexableField> fields = doc.getFields();
            for (IndexableField field : fields) {
                System.out.println(JSON.toJSONString(field));
            }
        }

        System.out.println("----------------------------------------------");

        // 创建查询对象
        Query query1 = IntPoint.newRangeQuery("price", 100, 1000);
        TopDocs topDocs1 = indexSearcher.search(query1, 10);
        ScoreDoc[] scoreDocs1 = topDocs1.scoreDocs;
        for (ScoreDoc scoreDoc : scoreDocs1) {
            int id = scoreDoc.doc;
            Document doc = indexSearcher.doc(id);
            List<IndexableField> fields = doc.getFields();
            for (IndexableField field : fields) {
                System.out.println(JSON.toJSONString(field));
            }
        }

        reader.close();
        return JSON.toJSONString("aok");
    }
}
